package accs.model.staemme;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import accs.model.Account;
import accs.model.AccountChecker;
import accs.model.Context;
import accs.model.ExtendedHttpClient;
import accs.model.utils.HeaderUtils;

public class DieStaemmeAccountChecker implements AccountChecker {

	public DSAccount login(String user, String password, Context ctx) throws Exception {
		ExtendedHttpClient client=new ExtendedHttpClient(ctx);
		
		HttpPost post=new HttpPost("/index.php?action=login&server_list=1&show_server_selection=1");
		post.setHeader(HeaderUtils.getReferer("http://www.die-staemme.de/index.php"));
		List<NameValuePair> list=new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("user",user));
		list.add(new BasicNameValuePair("password",password));
		list.add(new BasicNameValuePair("cookie","false"));
		list.add(new BasicNameValuePair("clear","true"));
		post.setEntity(new UrlEncodedFormEntity(list,"utf-8"));
		
		HttpResponse resp=client.execute(new HttpHost("www.die-staemme.de"),post);
		String res=EntityUtils.toString(resp.getEntity());
				
		JSONObject json=new JSONObject(res);
		
		if(json.has("error")) {
			return null;
		}
		
		return new DSAccount(user, password);
	}

	public String getName() {
		return "die_staemme";
	}

	public URL getImage() {
		return DieStaemmeAccountChecker.class.getResource("/accs/gui/img/ds.png");
	}
	
	private class DSAccount implements Account {
		private String mail;
		private String password;
		
		public DSAccount(String mail, String password) {
			super();
			this.mail = mail;
			this.password = password;
		}
		
		public String toString() {
			return mail+":"+password;
		}
	}
}